package com.forest.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.forest.config.SignatureProperties;
import com.forest.dto.AuthDTO;
import com.forest.dto.AuthEncryptionDTO;
import com.forest.dto.ResultResponse;
import com.forest.util.EnvironmentHolder;
import com.forest.util.SignParamUtil;

import java.util.Map;

/**
 * 签名调用接口.
 * @author Administrator
 */
public class SignatureHttpUtil {

    /**
     * 签名调用接口(post).
     *
     * @param appId     签名应用ID
     * @param url       业务请求地址
     * @param data      业务参数
     * @param <T>
     * @return
     */
    public static <T> ResultResponse<T> post(String appId, String url, Object data) {
        //获取app信息
        SignatureProperties.AppInfo appInfo = EnvironmentHolder.getAppInfo(appId);
        Assert.notNull(appInfo, "appId不存在");
        //构建签名参数
        AuthDTO authDTO = SignParamUtil.buildParam(appId, data);
        String result = HttpUtil.post(EnvironmentHolder.getSignatureHost() + url, JSONUtil.toJsonStr(authDTO));
        return Convert.convert(ResultResponse.class, JSONObject.parseObject(result));
    }

    /**
     * 签名调用接口-所有参数加密传输(post).
     *
     * @param appId     签名应用ID
     * @param url       业务请求地址
     * @param data      业务参数
     * @param <T>
     * @return
     */
    public static <T> ResultResponse<T> postForEncryption(String appId, String url, Object data) {
        //获取app信息
        SignatureProperties.AppInfo appInfo = EnvironmentHolder.getAppInfo(appId);
        Assert.notNull(appInfo, "appId不存在");
        //构建签名参数
        AuthEncryptionDTO authEncryptionDTO = SignParamUtil.buildEncryptionParam(appId, data);
        String result = HttpUtil.post(EnvironmentHolder.getSignatureHost() + url, JSONUtil.toJsonStr(authEncryptionDTO));
        return Convert.convert(ResultResponse.class, JSONObject.parseObject(result));
    }

    /**
     * 签名调用接口(get).
     *
     * @param appId     签名应用ID
     * @param url       业务请求地址
     * @param data      业务参数
     * @param <T>
     * @return
     */
    public static <T> ResultResponse<T> get(String appId, String url, Object data) {
        //获取app信息
        SignatureProperties.AppInfo appInfo = EnvironmentHolder.getAppInfo(appId);
        Assert.notNull(appInfo, "appId不存在");
        //构建签名参数
        AuthDTO authDTO = SignParamUtil.buildParam(appId, data);
        Map<String, Object> params = SignParamUtil.buildGetParam(authDTO);
        url = EnvironmentHolder.getSignatureHost() + url;
        if(MapUtil.isNotEmpty(params)) {
            url = url + "?";
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                url = url + entry.getKey() + "=" + entry.getValue() + "&";
            }
        }
        String result = HttpUtil.get(url);
        return JSONUtil.toBean(result, ResultResponse.class);
    }

}
